/*
 * @Description: 
 * @Version: 2.0
 * @Date: 2024-04-30 11:11:38
 * @LastEditTime: 2024-04-30 11:13:53
 */

// 计时器函数钩子 处理
import { ref, watch, onUnmounted } from 'vue';

export function UseInterval(
  // 回调函数
  callback: () => void,
  // 计时器时间，null 则不执行
  delay?: number | null,
  // 是否开启定时器，默认开启
  isOpen: boolean = true
) {
  const savedCallback = ref(callback);

  // 监视 callback 的变化，更新 ref
  watch(() => callback, () => {
    savedCallback.value = callback;
  });

  // 监视 delay 和 isOpen 的变化来控制计时器
  watch([() => delay, () => isOpen], ([newDelay, newIsOpen]) => {
    let intervalId: ReturnType<typeof setInterval> | null = null;

    if (!newIsOpen) {
      if (intervalId) {
        clearInterval(intervalId);
      }
      return;
    }

    if (newDelay === null || newDelay === undefined) {
      return;
    }

    intervalId = setInterval(() => {
      savedCallback.value();
    }, newDelay);

    // 组件卸载时清理定时器
    onUnmounted(() => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    });
  }, { immediate: true });
}
